package org.example.day10;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 4.1.4:正确使用Condition实现等待/通知
 *      注意：
 *          ①Object中的wait() 相当于 Condition类中的await()
 *          ②Object中的notify() 相当于 Condition类中的signal()
 *          ③Object中的notifyAll() 相当于Condition类中的signalAll()
 */
public class MyThread9 {
    private Lock lock = new ReentrantLock();
    public Condition condition = lock.newCondition();
    public void await(){
        try {
            lock.lock();
            System.out.println("await时间为: " + System.currentTimeMillis());
            condition.await();
            System.out.println("被唤醒继续执行");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public void signal(){
        try {
            lock.lock();
            System.out.println("signal时间为: " + System.currentTimeMillis());
            condition.signal();
        } finally {
            System.out.println("signal释放的锁");
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyThread9 m9 = new MyThread9();
        Thread9A ta = new Thread9A(m9);
        ta.start();
        Thread.sleep(3000);
        m9.signal();
    }
}

class Thread9A extends Thread{
    private MyThread9 m9;

    public Thread9A(MyThread9 m9) {
        this.m9 = m9;
    }

    @Override
    public void run() {
        m9.await();
    }
}